import 'package:flutter/material.dart';
import 'package:flutterdemo/dao/search_dao.dart';
import 'package:flutterdemo/model/seach_model.dart';
import 'package:flutterdemo/pages/home_page.dart';
import 'package:flutterdemo/pages/speak_page.dart';
import 'package:flutterdemo/util/navigator_util.dart';
import 'package:flutterdemo/widget/search_bar.dart';
import 'package:flutterdemo/widget/webview.dart';

const TYPES = [
  'channelgroup',
  'gs',
  'plane',
  'train',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup'
];

const URL = 'https://m.ctrip.com/restapi/h5api/globalsearch/search?source=mobileweb&action=mobileweb&keyword=';

class SearchPage extends StatefulWidget {

  final bool? hideLeft;
  final String searchUrl;
  final String? keyword;
  final String? hint;

  const SearchPage(
      {Key? key, this.hideLeft, this.searchUrl = URL, this.keyword, this.hint})
      : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  SearchModel? searchModel;
  String? keyword;

  @override
  void initState() {
    if (widget.keyword != null) {
      _onTextChange(widget.keyword!);
    }
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          _appBar(),
          MediaQuery.removePadding(
            //移除顶部的padding
            removeTop: true,
              context: context,
              //利用expanded使listview占据垂直布局 除了其他布局以为的其他空间
              child: Expanded(
                //自适应宽度和高度
                flex: 1,
                child: ListView.builder(
                    itemCount: searchModel?.data?.length ?? 0,
                    itemBuilder: (BuildContext context, int position) {
                      return _item(position);
                    }),
              ),
          )
        ],
      ),
    );
  }

  _onTextChange(String text) {
    keyword = text;
    if (text.length == 0) {
      setState(() {
        searchModel = null;
      });
      return;
    }
    //考虑url会不会定期的更新 优先服务端配置返回的searchUrl
    String url = '${(HomePage.configModel?.searchUrl ?? widget.searchUrl)}$text';
    SearchDao.fetch(url, text).then((SearchModel model) {
      //只有当当前输入的内容和服务端里存储的内容一致就可以渲染
      if (model.keyword == keyword) {
        setState(() {
          //对 searchmodel 进行赋值
          searchModel = model;
        });
      }
    }).catchError((e) {
      print(e);
    });
  }

  _appBar() {
    return Column(
      children: <Widget>[
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              //Appbar渐变的背景 定义起始颜色
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            )
          ),
          child: Container(
              padding: const EdgeInsets.only(top: 25),
              height: 80,
              decoration: const BoxDecoration(color: Colors.white),
              child: SearchBar(
                hideLeft: widget.hideLeft,
                defaultText: widget.keyword,
                hint: widget.hint,
                speakClick: _jumpToSpeak,
                rightButtonClick: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                leftButtonClick: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  Navigator.pop(context);
                },
                onChanged: _onTextChange,//
              ),
          ),
        )
      ],
    );
  }

  _jumpToSpeak() {
    NavigatorUtil.push(context, const SpeakPage());
  }
   _item(int position) {
      //在使用具体的成员变量的时候进行异常判断
      if (searchModel == null || searchModel?.data == null) return null;
      SearchItem item = searchModel!.data![position];
      return GestureDetector(
        onTap: () {
          NavigatorUtil.push(context,
            HiWebView(
              url: item.url!,
              title: '详情',
            ));
        },
        child: Container(
          padding: const EdgeInsets.all(10),
          decoration: const BoxDecoration(
            border: Border(bottom: BorderSide(width: 0.3, color: Colors.grey))),
          child: Row(
            children: <Widget>[
              Container(
                margin: const EdgeInsets.all(1),
                child: Image(
                  height: 26,
                  width: 26,
                  image: AssetImage(_typeImage(item.type))),
              ),
              Column(
                children: <Widget>[
                  Container(
                    width: 300,
                    child: _title(item),
                  ),
                  Container(
                    width: 300,
                    margin: EdgeInsets.only(top: 5),
                    child: _subTitle(item))
                ],
              )
            ],
          ),
        ),
      );
   }

  _typeImage(String? type) {
    if (type == null) return 'images/type_travelgroup.png';
    String path = 'travelgroup';
    for (final val in TYPES) {
      if (type.contains(val)) {
        path = val;
        break;
      }
    }
    return 'images/type_$path.png';

  }

  _title(SearchItem? item) {
    if (item == null) {
      return null;
    }
    List<TextSpan> spans = [];
    spans.addAll(_keywordTextSpans(item.word, searchModel!.keyword!));
    spans.add(TextSpan(
        text: ' ' + (item.districtname ?? '') + ' ' + (item.zonename ?? ''),
        style: const TextStyle(fontSize: 16, color: Colors.grey)));
    return RichText(text: TextSpan(children: spans));
  }

  _subTitle(SearchItem item) {
    return RichText(
      text: TextSpan(children: <TextSpan>[
        TextSpan(
          text: item.price ?? '',
          style: const TextStyle(fontSize: 16, color: Colors.orange),
        ),
        TextSpan(
          text: ' ' + (item.star ?? ''),
          style: const TextStyle(fontSize: 12, color: Colors.grey),
        )
      ]),
    );
  }

  _keywordTextSpans(String? word, String keyword) {
    List<TextSpan> spans = [];
    if (word == null || word.length == 0) return spans;
    //搜索关键词提示颜色忽略大小写
    String wordL = word.toLowerCase(),
        keywordL = keyword.toLowerCase();
    List<String> arr = wordL.split(keywordL);
    TextStyle normalStyle = const TextStyle(fontSize: 16, color: Colors.black87);
    TextStyle keywordStyle = const TextStyle(fontSize: 16, color: Colors.orange);
    int preIndex = 0;
    for (int i = 0; i < arr.length; i++) {
      if (i != 0) {
        preIndex = wordL.indexOf(keywordL, preIndex);
        spans.add(TextSpan(
            text: word.substring(preIndex, preIndex + keyword.length),
            style: keywordStyle));
      }
      String val = arr[i];
      if (val != null && val.length > 0) {
        spans.add(TextSpan(text: val, style: normalStyle));
      }
    }
    return spans;

  }

}


